package org.zetaframework.base.excel.handler;

import cn.idev.excel.write.handler.SheetWriteHandler;
import cn.idev.excel.write.handler.context.SheetWriteHandlerContext;
import org.apache.poi.ss.usermodel.DataValidation;
import org.apache.poi.ss.usermodel.DataValidationConstraint;
import org.apache.poi.ss.usermodel.DataValidationHelper;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddressList;

/**
 * 自定义下拉框处理器
 *
 * @author gcc
 */
public class DropdownHandler implements SheetWriteHandler {

    private final CellRangeAddressList range;
    private final String[] value;

    /**
     * 构造方法
     * <p>
     * 说明：
     * <pre>
     * Excel行列对应关系：
     * 行: 0=第1行, 1=第2行, 2=第3行...
     * 列: 0=A列, 1=B列, 2=C列, 3=D列...
     *
     * // 常用范围示例：
     * new CellRangeAddressList(0, 0, 0, 0);    // A1单元格
     * new CellRangeAddressList(1, 1, 0, 2);    // A2:C2。即：A2、B2、C2
     * new CellRangeAddressList(2, 5, 1, 1);    // B3:B6
     * new CellRangeAddressList(0, 999, 0, 0);  // A列前1000行
     * </pre>
     *
     *
     * @param range 字段所在下拉框区域
     * @param value 下拉框可选值
     */
    public DropdownHandler(CellRangeAddressList range, String[] value) {
        this.range = range;
        this.value = value;
    }

    /**
     * 在单元格创建之后执行
     */
    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        Sheet sheet = context.getWriteSheetHolder().getSheet();

        // 获取数据验证帮助器
        DataValidationHelper helper = sheet.getDataValidationHelper();
        // 创建下拉框约束
        DataValidationConstraint constraint = helper.createExplicitListConstraint(value);
        // 创建数据验证
        DataValidation validation = helper.createValidation(constraint, range);
        // 添加到sheet
        sheet.addValidationData(validation);
    }
}
